package com.mai4j.maiadmin.validation.constraintvalidators;


import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.mai4j.maiadmin.validation.constraints.IntlTel;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * Created by 席有芳 on 2021/12/2.
 * 国际电话号码校验器
 *
 * @author 席有芳
 */
public class IntTelValidator implements ConstraintValidator<IntlTel, String> {

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StringUtils.isBlank(value)) return true;
        try {
            PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
            Phonenumber.PhoneNumber phoneNumber = phoneNumberUtil.parse(value, "CN");
            return phoneNumberUtil.isValidNumber(phoneNumber);
        } catch (Exception ignore) {
            return false;
        }
    }
}
